#include "DataSerialportClient.h"
#include <QNetworkDatagram>

extern int expStatus;//实验状态 0空闲 1实验中 2暂停
extern QVector<double> cpsPartData;
extern bool isProductTesting;//产物检测
extern QString dataThresholdType;
extern double dataThreshold;

DataSerialportClient::DataSerialportClient(QObject *parent): QObject(parent)
{
    this->moveToThread(&thread);
    serialPort = new QSerialPort(this);
    thread.start();
}

void DataSerialportClient::startAutoSend(int intervalMs,QString serialNamePort){
    if(serialPort->isOpen()){
        serialPort->close();
    }else{
        QSerialPort::BaudRate baudRate;
        baudRate = QSerialPort::Baud115200;
        serialPort->setPortName(serialNamePort);
        serialPort->setBaudRate(baudRate);
        if(serialPort->open(QIODevice::ReadWrite)){
            connect(serialPort,SIGNAL(readyRead()),this,SLOT(handleReadyRead()));// 串口读取

            timer = new QTimer(this);
            connect(timer, &QTimer::timeout, this, &DataSerialportClient::sendMessage);
            timer->start(intervalMs);
        }
    }
}


void DataSerialportClient::sendMessage()
{
    if(expStatus==1||expStatus==2){
        QString message ="01 04 00 00 00 02 71 CB";
        QByteArray data = commonClient->GetSendData(message);
        serialPort->write(data);
    }
}

void DataSerialportClient::handleReadyRead()
{
    QByteArray data = serialPort->readAll();
    QString str;
    for(int c :data)
    {
        if(c>=0)
        {
            str += QString(" %1").arg(c, 2, 16, QChar('0')).toUpper();
        }
        else
        {
            str += QString(" %1").arg(c+256, 2, 16, QChar('0')).toUpper();
        }
    }
    str= str.simplified();

    QStringList list=str.split(" ");

    logClient->WriteLog("SpectralDetectionLog",QString("%1:\n"+str).arg("接收"));

    double finalData=commonClient->SixteenToTen(list[3]+" " +list[4]+" "+list[5]+" "+list[6]).toDouble();

    if(isProductTesting){
        if(dataThresholdType=="大于"){
            if(finalData>dataThreshold){
                isProductTesting=false;
                ExperimentThread::I().run();
            }
        }
        else if(dataThresholdType=="小于"){
            if(finalData<dataThreshold){
                isProductTesting=false;
                ExperimentThread::I().run();
            }
        }
    }
    cpsPartData.append(finalData);
}
